package com.tecklab.demo.easyrules;

import com.tecklab.demo.utils.LogConsolehUtils;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Fact;
import org.jeasy.rules.annotation.Rule;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.core.DefaultRulesEngine;

@Slf4j
@Rule(name = "order discount rule", description = "if order total money >= 300, then 10% discount")
public class PojoRuleTest {

    @Condition
    public boolean valid(@Fact("order") Order order) {
        if (order.getTotal() >= 300) {
            return true;
        } else {
            return false;
        }
    }

    @Action
    public void discount(@Fact("order") Order order) {
        log.info("order.total>=300, 10% discount!");
        order.setDiscount(0.1f);

    }

    public static void main(String[] args) {
        // 关闭日志框架日志打印
        LogConsolehUtils.setInfoLevel();

        Rules rules = new Rules();
        rules.register(new PojoRuleTest());

        RulesEngine rulesEngine = new DefaultRulesEngine();

        // define facts
        Facts facts = new Facts();
        Order order = Order.builder()
                .orderId("001")
                .total(300)
                .build();
        facts.put("order", order);

        rulesEngine.fire(rules, facts);
        log.info("order.discount: {}", order.getDiscount());

        order = Order.builder()
                .orderId("002")
                .total(200)
                .build();
        facts.put("order", order);
        
        rulesEngine.fire(rules, facts);
        log.info("order.discount: {}", order.getDiscount());
    }
}